package view;

import java.io.*;
import utils.Tools;
import javax.swing.*;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class AddStudentView {
    private JFrame frame;
    private JTextField StudentNameField;
    private JTextField studentIdField;
    private JComboBox<String> groupComboBox;
    private final int WIDTH = 400;
    private final int HEIGHT = 300;

    public AddStudentView() {
        frame = new JFrame("新增学生");
        initView();
        frame.setLayout(null);
        frame.setResizable(false);
        Tools.setPos(frame, WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setVisible(true);
    }

    private void initView() {
        // 创建学号标签和输入框
        JLabel idLabel = new JLabel("学号：");
        idLabel.setBounds(50, 50, 150, 30);
        frame.add(idLabel);

        studentIdField = new JTextField();
        studentIdField.setBounds(200, 50, 150, 30);
        frame.add(studentIdField);

        // 创建姓名标签和输入框
        JLabel nameLabel = new JLabel("姓名：");
        nameLabel.setBounds(50, 90, 150, 30);
        frame.add(nameLabel);

        StudentNameField = new JTextField();
        StudentNameField.setBounds(200, 90, 150, 30);
        frame.add(StudentNameField);

        // 创建小组选择下拉框
        JLabel groupLabel = new JLabel("选择小组：");
        groupLabel.setBounds(50, 130, 150, 30);
        frame.add(groupLabel);

        groupComboBox = new JComboBox<>();
        groupComboBox.setBounds(200, 130, 150, 30);
        loadGroups(); // 加载小组列表
        frame.add(groupComboBox);

        // 调整其他按钮的位置
        JButton submitBtn = new JButton("提交");
        submitBtn.setBounds(150, 180, 100, 30);
        submitBtn.addActionListener(e -> saveStudent());
        frame.add(submitBtn);

        JButton backBtn = new JButton("返回主页");
        backBtn.setBounds(150, 230, 100, 30);
        backBtn.addActionListener(e -> {
            frame.dispose();
            new MainView();
        });
        frame.add(backBtn);
    }

    // 加载小组列表
    private void loadGroups() {
        try {
            BufferedReader br = new BufferedReader(new FileReader("resources/Group.txt"));
            String line;
            while ((line = br.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    groupComboBox.addItem(line.trim());
                }
            }
            br.close();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(frame, "加载小组列表失败：" + e.getMessage());
        }
    }

    //新增学生的逻辑
    private void saveStudent() {
        String studentId = studentIdField.getText().trim();
        String studentName = StudentNameField.getText().trim();
        String selectedGroup = (String) groupComboBox.getSelectedItem();

        if (studentId.isEmpty() || studentName.isEmpty() || selectedGroup == null) {
            JOptionPane.showMessageDialog(frame, "请填写完整信息！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            // 检查学号是否已存在
            if (isStudentExists(studentId)) {
                JOptionPane.showMessageDialog(frame, "该学号已存在！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 保存格式：学号,姓名,小组名
            FileWriter fw = new FileWriter("resources/Student.txt", true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(studentId + "," + studentName + "," + selectedGroup);
            bw.newLine();
            bw.close();

            JOptionPane.showMessageDialog(frame, "学生添加成功！");
            studentIdField.setText("");
            StudentNameField.setText("");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(frame, "保存失败：" + e.getMessage());
        }
    }

    //检查学生是否存在
    private boolean isStudentExists(String studentId) {
        try {
            File file = new File("resources/Student.txt");
            if (!file.exists()) {
                return false;
            }

            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length > 0 && parts[0].trim().equals(studentId)) {
                    br.close();
                    return true;
                }
            }
            br.close();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}